package tech.mobi.child;

import java.util.HashMap;


import tech.mobi.child.base.BaseAct;
import tech.mobi.child.bean.UserInfoBean;
import tech.mobi.child.service.MainService;
import tech.mobi.child.setting.HelpMainAct;
import tech.mobi.child.utils.Configuration;
import tech.mobi.child.utils.Task;
import tech.mobi.child.utils.TaskType;
import tech.mobi.child.utils.Tools;
import tech.mobi.child.utils.UserInfo;
import tech.mobi.child.R;

import com.umeng.update.UmengUpdateAgent;
//import org.mymmsc.api.assembly.Helpers;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class LoginAct extends BaseAct implements OnClickListener {

	private ImageButton ibtnPassword;
	private boolean isPassword = false;// 没有勾选记住密码，ibtnPassword.background设置为checkbox_nor.png
	private EditText etUsername;
	private EditText etPassword;
	private String username;
	private String password;
	private Button btnLogin;
	private TextView tvVersionName;
//	private ProgressDialog progressDialog = null;
	private AnimationDrawable loadingAnimation;
	private ImageView ivLoginLoading;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_client_main);
		ibtnPassword = (ImageButton) this.findViewById(R.id.ibtnPassword);
		ibtnPassword.setOnClickListener(this);

		etUsername = (EditText) this.findViewById(R.id.etUserName);
		etPassword = (EditText) this.findViewById(R.id.etPassword);
		tvVersionName = (TextView) this.findViewById(R.id.tvVersionName);
		tvVersionName.setText(getText(R.string.login_version_name)
				+ getVersionName());
		ivLoginLoading = (ImageView) this.findViewById(R.id.ivLoginLoading);
		ivLoginLoading.setVisibility(View.GONE);
		
		String username = UserInfo.getUserName(this);
		String password = UserInfo.getPassword(this);
		
		if (!("".equals(username)) && !("".equals(password))) {
			etUsername.setText(username);
			etPassword.setText(password);
			setPasswordChecked(isPassword);

		}
		// else{
		// String number = getPhoneNumber();
		// if(number!=null&&!"".equals(number)){
		// etUsername.setText(number.replace("+86", ""));
		// }
		// }

		btnLogin = (Button) this.findViewById(R.id.btnLogin);
		btnLogin.setOnClickListener(this);

		// 友盟自动更新
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.update(this);

	}


	private void loadingData() {
		ivLoginLoading.setVisibility(View.VISIBLE);
		//loginLoading.setBackgroundResource(R.anim.login_loading); 
		loadingAnimation = (AnimationDrawable) ivLoginLoading.getBackground();
		ivLoginLoading.post(new Runnable()
		 {
			@Override
			public void run()

			{
				loadingAnimation.start();
			}
		});
	}
	
	
	/**
	 * 得到版本号
	 */
	private String getVersionName() {
		String versionName = "";
		PackageManager packageManager = this.getPackageManager();
		try {
			PackageInfo packageInfo = packageManager.getPackageInfo(
					this.getPackageName(), 0);
			versionName = packageInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionName;
	}

	@Override
	public void init() {

	}

	@Override
	public void refresh(Object... param) {
		int taskType = (Integer) param[0];
		if (taskType == TaskType.TASK_LOGIN) {
//			if (progressDialog != null && progressDialog.isShowing()) {
//				progressDialog.cancel();
//			}
			btnLogin.setEnabled(true);

			if (param[1] != null) {
				String status = "";
				String message = "";

				UserInfoBean userInfoBean = (UserInfoBean) param[1];
				status = userInfoBean.getStatus();
				message = userInfoBean.getMessage();

				if (status != null) {
					if (status.equals(Configuration.EXP_SUCCESS)) {
						/******************************/
						//TODO 将登录用户信息写入内容提供者。
						UserInfo.setUserId(this, userInfoBean.getUserid());
						UserInfo.setUserName(this, userInfoBean.getUsername());
						UserInfo.setPassword(this, userInfoBean.getPassword());
						UserInfo.setTrueName(this, userInfoBean.getTurename());
						UserInfo.setUserSex(this, userInfoBean.getUsersex());
						UserInfo.setUserType(this, userInfoBean.getUsertype());
						
						if (isPassword) {
							UserInfo.setAutoLogin(this, "yes");
						} else {
							UserInfo.setAutoLogin(this, "no");
						}
						/******************************/
						
						int iVersion = 0;
						int iVersionCur = 0;
						try {
							iVersionCur = Integer.parseInt(Tools
									.getVersionName(this).replace(".", ""));
							iVersion = Integer.parseInt(UserInfo.getVersion(this));

						} catch (Exception exx) {
							iVersion = 0;
						}

						if (iVersionCur > iVersion) {
							// 增加新功能提示功能
							Intent intent = new Intent(this, HelpMainAct.class);
							this.startActivity(intent);
						} else {
							Intent intent = new Intent(this, MainAct.class);
							this.startActivity(intent);
						}

						finish();
					}
					ivLoginLoading.setVisibility(View.GONE);

					Toast.makeText(this, message, Toast.LENGTH_LONG).show();
				} else {
					ivLoginLoading.setVisibility(View.GONE);
					Toast.makeText(this, "系统正忙，请稍等！", Toast.LENGTH_LONG).show();
				}

			} else {
				ivLoginLoading.setVisibility(View.GONE);
				Toast.makeText(this, "系统正忙，请稍等！", Toast.LENGTH_LONG).show();
			}

		}

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ibtnPassword:
			setPasswordChecked(isPassword);
			break;

		case R.id.btnLogin:

			username = this.etUsername.getText().toString().trim();
			password = this.etPassword.getText().toString().trim();
			if ("".equals(username)) {
				Toast.makeText(this, R.string.login_username_empty,
						Toast.LENGTH_LONG).show();
			} else if ("".equals(password)) {
				Toast.makeText(this, R.string.login_password_empty,
						Toast.LENGTH_LONG).show();
			} else {
				btnLogin.setEnabled(false);

				loadingData();
//				progressDialog = ProgressDialog.show(this, "",
//						getText(R.string.login_logining));
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("username", username);
				map.put("password", password);
				map.put("flag", Configuration.APP_FLAG);
				map.put("version", Tools.getVersionName(this));
				Task task = new Task(TaskType.TASK_LOGIN, map);
				MainService.newTask(task);

			}
			break;
		}

	}

	/**
	 * 设置ibtnPassword的背景，并修改isPassword的值
	 * 
	 * @param b
	 */
	private void setPasswordChecked(boolean b) {
		if (!b) {
			ibtnPassword.setBackgroundResource(R.drawable.checkbox_checked);
		} else {
			ibtnPassword.setBackgroundResource(R.drawable.checkbox_nor);
		}
		isPassword = (b == false ? true : false);
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}
